#include "client.h"
int threadPoolInit(threadPool *pThreadPool, int worker_num)
{
    pThreadPool->thread_num = worker_num;
    pThreadPool->pTid = (pthread_t *)calloc(worker_num, sizeof(pthread_t));
    pThreadPool->taskQueue.pFront = NULL;
    pThreadPool->taskQueue.pRear = NULL;
    pThreadPool->taskQueue.size = 0;
    pthread_mutex_init(&pThreadPool->taskQueue.mutex, NULL);
    pthread_cond_init(&pThreadPool->taskQueue.cond, NULL);
    pThreadPool->exitFlag = 0;
}
void cleanFunc(void *arg)
{
    threadPool *pThreadPool = (threadPool *)arg;
    pthread_mutex_unlock(&pThreadPool->taskQueue.mutex);
}
void *handleEvent(void *arg)
{
    threadPool *pThreadPool = (threadPool *)arg;
    int net_fd;
    while (1)
    {
        printf("I am free tid = %lu\n", pthread_self());
        pthread_mutex_lock(&pThreadPool->taskQueue.mutex);
        pthread_cleanup_push(cleanFunc, (void *)pThreadPool);
        while (pThreadPool->taskQueue.size == 0 && pThreadPool->exitFlag == 0)
        {
            pthread_cond_wait(&pThreadPool->taskQueue.cond, &pThreadPool->taskQueue.mutex);
        }
        if (pThreadPool->exitFlag != 0)
        {
            printf("I am going to die chile thread!\n");
            pthread_exit(NULL);
        }
        // 子线程苏醒
        net_fd = pThreadPool->taskQueue.pFront->netfd; // 唤醒队列队首文件描述符
        taskDequeue(&pThreadPool->taskQueue);
        pthread_cleanup_pop(1);
        printf("i am working!  client tid = %lu\n", pthread_self());
        
       localTasks(net_fd);
        printf("done\n");
        close(net_fd);
    }
}
int taskEnqueue(taskQueues *pTaskQueue, int netfd)
{
    tasks *pTask = (tasks *)calloc(1, sizeof(tasks));
    pTask->netfd = netfd;
    if (pTaskQueue->size == 0)
    {
        pTaskQueue->pFront = pTask;
        pTaskQueue->pRear = pTask;
    }
    else
    {
        pTaskQueue->pRear->pNext = pTask;
        pTaskQueue->pRear = pTask;
    }
    ++pTaskQueue->size;
    return 0;
}

int taskDequeue(taskQueues *pTaskQueue)
{
    tasks *pCur = pTaskQueue->pFront;
    pTaskQueue->pFront = pCur->pNext;
    free(pCur);
    --pTaskQueue->size;
    return 0;
}

int makeWorker(threadPool *pThreadPool)
{
    for (size_t i = 0; i < pThreadPool->thread_num; i++)
    {
        pthread_create(&pThreadPool->pTid[i], NULL, handleEvent, (void *)pThreadPool);
    }
}
